<template>
  <div class="tab_plugins">
    <div class="category"
         ref="categoryRef">
      <div class="category_item"
           v-for="(item, index) in categories"
           :class="{current: currentIndex == index}"
           :key="index"
           @click="selectItem(index)">{{item.label}}</div>
    </div>
    <div class="main"
         ref="mainRef">
      <div class="top_banner">
        <Banner></Banner>
      </div>
      <div class="plugin_group"
           v-for="(item, index) in categories"
           :key="index">
        <div class="plugin_group_title"
             v-text="item.label"></div>
        <div class="plugin_group_main">
          <div class="plugin_group_main_item"
               v-for="(itm, idx) in item.list"
               :key="idx"
               @click="gotoPluginDetail(itm)">
            <div class="item_logo">
              <img :src="itm.logo"
                   alt="">
            </div>
            <div class="item_info">
              <div class="item_info_title"
                   v-text="itm.pluginName"></div>
              <div class="item_info_desc"
                   v-text="itm.description"></div>
            </div>

            <div class="item_append">
              <div class="item_append_inner"
                   v-if="(installedPlugins.indexOf(itm.pid) < 0) && (!downloading.hasOwnProperty(itm.pid))"
                   @click="downloadPlugin($event, itm)">
                <svg>
                  <use xlink:href="#icon-download"></use>
                </svg>
              </div>
              <Tooltip content="有新版本"
                       :transfer="true"
                       placement="top"
                       v-else-if="needUpgrade.hasOwnProperty(itm.pid)">
                <div class="item_append_inner plugin_upgrade"
                     style="overflow: hidden;"
                     :class="{active: upgrading.hasOwnProperty(itm.pid)}"
                     @click="upgradePlugin($event, itm)">
                  <div class="plugin_upgrade_icon">
                    <svg style="fill: green;">
                      <use xlink:href="#icon-upgrade"></use>
                    </svg>
                  </div>
                </div>
              </Tooltip>
              <div class="item_append_loading"
                   v-else-if="downloading.hasOwnProperty(itm.pid)">
                <img src="http://static.dei2.com/resources/loading.gif">
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <Drawer title="插件详情"
            :width="640"
            v-model="detailDrawer.shown"
            :closable="true">
      <div class="detail_drawer">
        <div class="detail_header">
          <div class="detail_header_left">
            <div class="detail_header_logo">
              <img :src="detailDrawer.data.logo"
                   alt="">
            </div>
          </div>
          <div class="detail_header_right">
            <div class="detail_header_right_top">
              <div class="detail_main_info">
                <div class="detail_main_info_top">
                  <div class="detail_name">
                    <div v-text="detailDrawer.data.pluginName"></div>
                    <div class="detail_version"
                         v-text="detailDrawer.data.version"></div>
                  </div>
                </div>
                <div class="detail_main_info_bottom">
                  <div>开发者: </div>
                  <a href="javascript:void(0)"
                     v-text="detailDrawer.data.author"
                     @click="openLink(detailDrawer.data.homepage, $event)"></a>
                  <div style="margin-left: 15px; margin-right: 8px;">大小: </div>
                  <div v-text="$sizeFormat(detailDrawer.data.size)"></div>
                </div>
              </div>
              <div class="detail_main_append">
                <Button type="primary"
                        v-if="(installedPlugins.indexOf(detailDrawer.data.pid) < 0)"
                        :loading="downloading.hasOwnProperty(detailDrawer.data.pid)"
                        @click="downloadPlugin($event, detailDrawer.data)"
                        size="small">
                  <span v-if="!downloading.hasOwnProperty(detailDrawer.data.pid)">下载</span>
                  <span v-else>下载中...</span>
                </Button>
                <Tooltip :content="'版本升级至 v' + needUpgrade[detailDrawer.data.pid].version"
                         :transfer="true"
                         placement="top"
                         v-else-if="needUpgrade.hasOwnProperty(detailDrawer.data.pid)">
                  <Button type="success"
                          size="small"
                          long
                          shape="circle"
                          :loading="upgrading.hasOwnProperty(detailDrawer.data.pid)"
                          @click="upgradePlugin($event, detailDrawer.data)">
                    <span v-if="!upgrading.hasOwnProperty(detailDrawer.data.pid)">升级</span>
                    <span v-else>升级中...</span>
                  </Button>
                </Tooltip>
                <Button type="error"
                        v-else
                        @click="uninstallPlugin($event, detailDrawer.data)"
                        size="small">
                  卸载
                </Button>
              </div>
            </div>
            <div class="detail_header_right_bottom"
                 v-text="detailDrawer.data.description"></div>
          </div>
        </div>
        <div class="detail_content"
             v-if="this.installedPlugins.indexOf(this.detailDrawer.data.pid) > -1">
          <PanelMain :info="detailDrawer.data"
                     style="width: 100%; left: 0;"
                     type="Plugins"></PanelMain>
        </div>
      </div>
    </Drawer>
  </div>
</template>

<script>
import { Drawer, Button, Tooltip } from 'view-design'
import { createNamespacedHelpers, mapState } from 'vuex'
const { mapActions } = createNamespacedHelpers('./store/modules')
export default {
  name: 'Plugins',
  components: {
    Drawer, Button, Tooltip,
    Banner: () => import('../common/Banner.vue'),
    PanelMain: () => import('./parts/PanelMain/index'),
  },
  props: {
    activeTab: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      // categories: [],
      scrollY: 0,
      detailDrawer: {
        shown: false,
        data: {}
      }
    }
  },
  watch: {
    activeTab: {
      immediate: true,
      handler (val) {
        if (val == 'Plugins') {
          this.initCategories()
        }
      }
    }
  },
  computed: {
    ...mapState(
      {
        downloading: (state) => state.modulePlugins.downloading,
        upgrading: (state) => state.modulePlugins.upgrading,
        needUpgrade: (state) => state.modulePlugins.needUpgrade,
        categories: (state) => state.moduleCategory.categories,
        installedPlugins: (state) => state.modulePlugins.normal.map(item => item.pid)
      }
    ),
    itemHeight () {
      if (this.categories.length == 0) return 0
      let a = Array(this.categories.length).fill([0, 0])
      for (let i = 0; i < this.categories.length; i++) {
        if (i == 0) {
          a[i] = [0, 260 + 64 + 64 * Math.ceil((this.categories[i]?.list?.length || 0) / 2)]
        } else {
          a[i] = [a[i - 1][1], a[i - 1][1] + 64 + 64 * Math.ceil((this.categories[i]?.list?.length || 0) / 2)]
        }
      }
      return a
    },
    currentIndex () {
      let index = 0
      for (let i = 0; i < this.itemHeight.length; i++) {
        if (this.scrollY >= this.itemHeight[i][0] && this.scrollY < this.itemHeight[i][1]) {
          index = i
          i = this.itemHeight.length
        }
      }
      return index
    }
  },
  mounted () {
    bbtools.on('category-list-response', this.categoryListResponse)
    bbtools.on('plugin-uninstall-response', this.pluginUninstallResponse)
  },
  methods: {
    ...mapActions([
      'modulePlugins'
    ]),
    upgradePlugin (e, item) {
      e.stopPropagation()
      bbtools.send('plugin-upgrade', item)
    },
    initCategories () {
      bbtools.send('category-list')
    },
    categoryListResponse (event, response) {
      this._initScroll()
    },
    _initScroll () {
      if (!this.$refs.mainRef) return
      this.$refs.mainRef.removeEventListener('scroll', this.scrollHandler)
      this.$refs.mainRef.addEventListener('scroll', this.scrollHandler)
    },
    scrollHandler (e) {
      this.scrollY = e.target.scrollTop
    },
    selectItem (index) {
      this.$scrollTo(this.scrollY, this.itemHeight[index][0], this.$refs.mainRef)
    },
    gotoPluginDetail (item) {
      this.detailDrawer.shown = true
      this.detailDrawer.data = item || {}
      // if (this.installedPlugins.indexOf(this.detailDrawer.data.pid) > -1) {
      //   if (this.detailDrawer.data.features) {
      //     this.detailDrawer.data.features = JSON.parse(this.detailDrawer.data.features)
      //     if (this.detailDrawer.data.features.searchable) {
      //       this.detailDrawer.data.features.searchable = JSON.parse(this.detailDrawer.data.features.searchable)
      //       if (this.detailDrawer.data.features.searchable.cmds) {
      //         this.detailDrawer.data.features.searchable.cmds = JSON.parse(this.detailDrawer.data.features.searchable.cmds)
      //       }
      //     }
      //   }
      // }
    },
    resetDetailDrawer () {
      this.detailDrawer.shown = false
      this.detailDrawer.data = {}
    },
    downloadPlugin (e, item) {
      e.stopPropagation()
      bbtools.send('plugin-install', Object.assign({}, item, {
        type: 'normal'
      }))
    },
    openLink (url, event) {
      event.preventDefault()
      bbtools.shell.openExternal(url)
    },
    pluginUninstallResponse (event, response) {
      if (response.step == 1) {
        this.resetDetailDrawer()
      } else { }
    },
    uninstallPlugin (e, data) {
      this.$Modal.confirm({
        title: '确认删除',
        content: '删除后无法恢复，请确认',
        cancelText: '取消',
        okText: '删除',
        onOk: () => {
          bbtools.send('plugin-uninstall', Object.assign({}, data, {
            type: 'normal'
          }))
        }
      })
    }
  },
}
</script>

<style lang="less" scoped>
@import url("../themes/index.less");
.tab_plugins {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  // align-items: center;
  // justify-content: center;
  .category {
    width: 160px;
    height: calc(~"100% - 36px");
    background-color: lighten(@darkDividerColor, 85);
    box-shadow: -20px -5px 22px -22px rgba(217, 217, 217, 0.8) inset;
    padding-top: 20px;
    box-sizing: border-box;
    &_item {
      width: 100%;
      height: 48px;
      cursor: pointer;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      color: @darkTextColor1;
      &.current {
        background-color: @activeBgColor;
        color: @darkPrimaryColor;
        font-weight: bold;
        // background-color: #eee;
      }
    }
  }
  .main {
    width: calc(~"100% - 160px");
    height: calc(~"100% - 36px");
    padding-bottom: 240px;
    overflow-y: auto;
    .top_banner {
      width: 100%;
      height: 260px;
      padding: 20px;
      box-sizing: border-box;
      border-bottom: 1px solid @darkDividerColor;
    }
    .plugin_group {
      width: 100%;
      &_title {
        width: 100%;
        height: 64px;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: flex-start;
        padding: 0 20px;
        box-sizing: border-box;
        font-size: 20px;
        font-weight: bold;
        color: @darkTextColor1;
      }
      &_main {
        width: 100%;
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
        padding: 0 5px;
        box-sizing: border-box;
        &_item {
          position: relative;
          width: 50%;
          height: 64px;
          padding: 10px 20px;
          box-sizing: border-box;
          cursor: pointer;
          border-radius: 4px;
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: space-between;
          &:hover {
            background-color: @activeBgColor;
          }
          .item_logo {
            width: 48px;
            height: 48px;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: flex-start;
            img {
              width: 34px;
              height: 34px;
              border-radius: 5px;
            }
          }
          .item_info {
            width: calc(~"100% - 48px");
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            &_title {
              width: 100%;
              height: 20px;
              white-space: nowrap;
              text-overflow: ellipsis;
              overflow: hidden;
              font-size: 16px;
              line-height: 20px;
              font-weight: bold;
              color: @darkTextColor2;
            }
            &_desc {
              width: 100%;
              height: 26px;
              white-space: nowrap;
              text-overflow: ellipsis;
              overflow: hidden;
              font-size: 12px;
              line-height: 26px;
              color: @darkTextColor3;
            }
          }
          .item_append {
            // position: relative;
            position: absolute;
            right: 0;
            top: 0;
            width: 30px;
            height: 48px;
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;
            &_inner {
              width: 100%;
              height: 100%;
              display: flex;
              flex-direction: row;
              align-items: center;
              // justify-content: flex-end;
              svg {
                width: 18px;
                height: 18px;
                fill: @darkTextColor3;
              }
            }
            &_loading {
              position: absolute;
              left: 0;
              top: 0;
              width: 100%;
              height: 100%;
              display: flex;
              flex-direction: row;
              align-items: center;
              // justify-content: flex-end;
              img {
                width: 18px;
                height: 18px;
              }
            }
          }
        }
      }
    }
  }
}
.detail_drawer {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .detail_header {
    width: 100%;
    height: 120px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    &_left {
      width: 120px;
      height: 120px;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: flex-start;
      .detail_header_logo {
        width: 96px;
        height: 96px;
        border-radius: 6px;
        box-sizing: border-box;
        overflow: hidden;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        img {
          max-width: 96px;
          max-height: 96px;
        }
      }
    }
    &_right {
      flex: 1;
      height: 120px;
      &_top {
        width: 100%;
        height: 60px;
        border-bottom: 1px solid @darkDividerColor;
        box-sizing: border-box;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
        .detail_main_info {
          flex: 1;
          height: 60px;
          padding-bottom: 4px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          &_top {
            width: 100%;
            height: 30px;
            display: flex;
            flex-direction: row;
            align-items: center;
            .detail_name {
              font-size: 16px;
              color: @darkTextColor1;
              font-weight: bold;
              display: flex;
              flex-direction: row;
              align-items: center;
              .detail_version {
                margin-left: 8px;
                padding: 0 8px;
                height: 24px;
                font-size: 12px;
                border-radius: 15px;
                box-sizing: border-box;
                display: flex;
                flex-direction: row;
                align-items: center;
                justify-content: center;
                background-color: @activeBgColor;
                color: @darkTextColor3;
              }
            }
            .detail_subinfo {
              display: flex;
              flex-direction: row;
              align-items: center;
            }
          }
          &_bottom {
            display: flex;
            flex-direction: row;
            align-items: center;
            color: @darkTextColor3;
            font-size: 12px;
            a {
              margin-left: 8px;
            }
          }
        }
        .detail_main_append {
          width: 100px;
          height: 60px;
          display: flex;
          flex-direction: row;
          align-items: flex-start;
          justify-content: flex-end;
        }
      }
      &_bottom {
        width: 100%;
        height: 40px;
        // padding: 10px 0;
        margin-top: 6px;
        line-height: 20px;
        overflow: hidden;
        display: -webkit-box;
        text-overflow: ellipsis;
        -webkit-line-clamp: 2; /*要显示的行数*/
        -webkit-box-orient: vertical;
        font-size: 12px;
        color: @darkTextColor3;
      }
    }
  }
  .detail_content {
    position: relative;
    width: 100%;
    flex: 1;
  }
}
</style>